<template>
  <div class="execution">
    <basic-container>
      <el-form :model="searchForm" ref="searchForm" :inline="true" size="small">
        <el-form-item label="流程KEY" prop="key">
          <el-input v-model="searchForm.key" placeholder="请输入流程KEY"
                  clearable size="small"/>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="searchForm.name" placeholder="请输入名称"
                  clearable size="small"/>
        </el-form-item>
        <div>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="searchSubmit">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="clearSearchForm">重置</el-button>
        </div>
      </el-form>
    </basic-container>
    <basic-container>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" size="mini"
                  @click="OnlineDrawingProcess">
            在线绘制流程
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" size="mini"
                  @click="handleImport">
            部署流程
          </el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="tableData">
        <el-table-column label="流程ID" align="center" prop="id"/>
        <el-table-column label="流程KEY" align="center" prop="key"/>
        <el-table-column label="流程名称" align="center" prop="name"/>
        <el-table-column label="版本" align="center" prop="version"/>
        <el-table-column label="部署时间" align="center" prop="deploymentTime"/>
        <el-table-column label="部署ID" align="center" prop="deploymentId"/>

        <el-table-column label="状态" align="center" prop="suspendState">
          <template slot-scope="scope">
            <span>{{ scope.row.suspendState!=1?'挂起':'激活'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit"
                    @click="OnlineModificationProcess(scope.row)">
              查看
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-edit"
                    @click="suspendOrActiveApply(scope.row)">
              {{scope.row.suspendState==1?'挂起':'激活'}}
            </el-button>

            <el-button size="mini" type="text" icon="el-icon-delete"
                       @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination background @prev-click="prePage" @next-click="nextPage" @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :page-sizes="[10, 25, 50]" :page-size="10"
              style="float:right;margin:10px 0" layout="total,sizes,prev, pager, next" :total="this.page.total">
      </el-pagination>
<!--      <pagination :total="total" :page.sync="queryParams.pageNum"-->
<!--              :limit.sync="queryParams.pageSize" @pagination="getList"/>-->
      <!--bpmnjs在线流程设计器-->
      <el-dialog :visible.sync="modelVisible" title="流程图" width="1080px"
              @close="modelCancel" append-to-body>
        <div style="position:relative;height: 100%;">
          <iframe id="iframe" :src="modelerUrl" frameborder="0" width="100%" height="720px" scrolling="auto"></iframe>
        </div>
      </el-dialog>

      <!-- 用户导入对话框 -->
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        部署名称: <el-input v-model = "upload.name" placeholder="请输入流程名称" style="width: 80%; margin-bottom: 5px"></el-input>
        <el-upload ref="upload" :limit="1" accept=".bpmn, .bar, .zip" :headers="upload.headers" :action="upload.url"
                   :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :data="{deploymentName: upload.name}"
                   :on-success="handleFileSuccess" :auto-upload="false" drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“bpmn”、“bar”或“zip”格式文件！</div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
  import {listDefinition, delDefinition, suspendOrActiveApply} from "@/api/activiti/definition";
  // import {getToken} from "@/utils/auth";
  import store from '@/store';
  import { baseUrl } from '@/config/env';
  import {getSearchForm} from "@/util/util";

  export default {
    name: "ActIdGroup",
    data() {
      return {
        modelerUrl: "",
        modelVisible: false,
        // 遮罩层
        loading: true,
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // // 总条数
        // total: 0,
        // VIEW表格数据
        // Modeler: [],
        tableData: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        src: "",
        // 查询参数
        // queryParams: {
        //   pageNum: 1,
        //   pageSize: 10,
        //   id: null,
        //   rev: null,
        //   name: null,
        //   type: null
        searchForm: {
          key: null,
          name: null,
        },
        // },
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 10 // 每页显示多少条
        },
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          name: null,
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + store.getters.access_token},
          // 上传的地址
          url: baseUrl + "/workflow/processDefinition/uploadStreamAndDeployment",
        },
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询Definition列表 */
      getList() {
        this.loading = true;
        const searchModel = Object.assign(
          {current: this.page.currentPage, size: this.page.pageSize},
          getSearchForm(this.searchForm),
        );
        listDefinition(searchModel).then(response => {
          // this.Modeler = response.data.data.records;
          if (response.data.code === 0) {
            this.tableData = response.data.data.records;
            this.page.total = response.data.total;
          } else {
            this.$message.error(response.data.msg);
          }
          this.loading = false;
        });
      },
      /** 搜索按钮操作 */
      searchSubmit() {
        this.page.currentPage = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      clearSearchForm() {
        this.$refs["searchForm"].resetFields();
        // this.searchSubmit();
      },

      suspendOrActiveApply(row) {
        var suspendOrActive = row.suspendState === '2' ? '激活' : '挂起';
        this.$confirm('确认要' + suspendOrActive + '流程定义吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          var data = {"id": row.id, "suspendState": row.suspendState};
          return suspendOrActiveApply(data);
        }).then(() => {
          this.getList();
          this.msgSuccess("转换成功");
        }).catch(function () {
        });


      },

      handleImport() {
        this.upload.title = "上传模型图";
        this.upload.open = true;
      },
      OnlineDrawingProcess() {
        this.modelVisible = true;
        localStorage.setItem("VUE_APP_BASE_API", baseUrl)
        // setStore({name: "VUE_APP_BASE_API", content: process.env.VUE_APP_BASE_API});
        this.modelerUrl = "/bpmnjs/index.html?type=addBpmn";
      },
      OnlineModificationProcess(data) {
        this.modelVisible = true;
        localStorage.setItem("VUE_APP_BASE_API", baseUrl)
        this.modelerUrl = '/bpmnjs/index.html?type=lookBpmn&deploymentFileUUID=' + data.deploymentId + '&deploymentName=' + encodeURI(data.resourceName);
      },

      // 提交上传文件
      submitFileForm() {
        if (this.upload.name) {
          this.$refs.upload.submit();
        } else {
          this.$message.error("流程名称不可为空");
        }
      },

      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.name = null;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        const result = response.data.code === 0 ? "导入成功" : "导入失败";
        this.$alert(result, "导入结果", {dangerouslyUseHTMLString: true});
        this.getList();
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        this.$confirm('是否确认删除编号为"' + row.key + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delDefinition(row.deploymentId);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
      },
      modelCancel() {
        this.getList();
      },

      //上一页
      prePage(val) {
        // this.page.currentPage--
        this.handleCurrentChange(val)
      },
      //下一页
      nextPage(val) {
        this.handleCurrentChange(val)
      },
      //当前页改变
      handleCurrentChange(val) {
        this.page.currentPage = val
        this.getList()
      },
      //每页数据条数
      handleSizeChange(val) {
        this.page.pageSize = val;
        this.getList()
      },

    }
  };
</script>
